import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:url_launcher/url_launcher.dart';

class MarkdownPage extends StatefulWidget {
  final parseFileString;
  final title;
  MarkdownPage({this.parseFileString = 'assets/CS61A.md',this.title = "test"});

  @override
  _MarkdownPageState createState() => _MarkdownPageState();
}

class _MarkdownPageState extends State<MarkdownPage> {
  String _mdData = '';

  @override
  void initState() {
    super.initState();
    _loadMarkdown();
  }

  Future<void> _loadMarkdown() async {
    final data = await rootBundle.loadString(widget.parseFileString);
    setState(() => _mdData = data);
  }

  Future<void> openUrl(String url) async {
    final uri = Uri.parse(url);

    if (await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication); // 或 LaunchMode.inAppWebView
    } else {
      throw 'Could not launch $url';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text(
            widget.title,
            style: TextStyle(fontFamily: "JetBrainsMono"),
          )
      ),
      body: _mdData.isEmpty
          ? Center(child: CircularProgressIndicator())
          : Markdown(
        data: _mdData,
        styleSheet: MarkdownStyleSheet(
          h1: TextStyle(fontFamily: "JetBrainsMono", fontSize: 35, fontWeight: FontWeight.bold),
          h2: TextStyle(fontFamily: "JetBrainsMono", fontSize: 25, fontWeight: FontWeight.bold),
          h3: TextStyle(fontFamily: "JetBrainsMono", fontSize: 20, fontWeight: FontWeight.bold),
          h4: TextStyle(fontFamily: "JetBrainsMono", fontSize: 15, fontWeight: FontWeight.bold),
          p:  TextStyle(fontFamily: "JetBrainsMono", fontSize: 15),
          a:  TextStyle(fontFamily: "JetBrainsMono", fontSize: 15),
        ),
        onTapLink: (text, href, title) {
          // 处理链接点击
          print('点击了链接: $href');
          openUrl("$href");
        },
      ),
    );
  }
}
